package tgc.edu.yzy.custom;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class CommonController<T,ID,Form extends CommonForm<ID>> {

	@Autowired
	private CommonService<T,ID> baseService;
	/***
	 * 获取一个实体类对象
	 */
	@SuppressWarnings("unchecked")
	private Class<T> clazz=GenericsUtils.getSuperClassGenricType(getClass());
	
	@RequestMapping(value="/pagelist")
	public Object list(DatagridUtils param) {
		Pageable pageable = param.buildPageable();
		Page<T> page=baseService.findAll(pageable);
		return param.getPageResult(page);
	}
	@RequestMapping(value="/edit")
	public void edit(ID id,ModelMap map) throws InstantiationException,IllegalAccessException{
		T model=clazz.newInstance();
		if(id!=null) {
			model=baseService.findById(id);
		}
		map.put("model", model);
	}
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(Form form) {
		try {
			T model=clazz.newInstance();
			ID id=form.getId();
			if(id!=null) {
				model=baseService.findById(id);
			}
			BeanUtils.copyProperties(form, model,"id");
			baseService.save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(Form form) {
		try {
			ID id = form.getId();
			baseService.deleteByID(id);
			return true;
		}catch (Exception e) {
			return false;
		}
	}
}
